import format from 'date-fns/format';
import axios from '../request/http'

const regString = '##;;'

const optionOrder = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']




export function delFirstAndLastPTag(str, keepSingleP = false) {
  let result = str
  if (result) {
    //应该用一个正则来处理空白换行符
    let startTag = ''
    let endTag = ''
    if (keepSingleP) {
      startTag = '<p>'
      endTag = '</p>'
    }
    result = result.replace(/^(<p>|<p style=\".+;\">|<br>|<\/p>)+/g, startTag)   //<span style=\".+;\">||<\/span><\/p>
    //debugger

    // if (result.endsWith('</p>'))
    result = result.replace(/(<p>|<p style=\".+;\">|<br>|<\/p>)+$/g, endTag)
  }

  return result
}

function formatDuring(mss) {
  var days = parseInt(mss / (1000 * 60 * 60 * 24));
  var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = (mss % (1000 * 60)) / 1000;
  return (hours === 0 ? '00' : hours.toFixed()) + ":" + (minutes === 0 ? '00' : minutes.toFixed()) + ":" + (seconds === 0 ? '00' : Number(seconds) < 10 ? "0" + seconds.toFixed() : seconds.toFixed())
}

function isBeforeTheTime(dateTimeStr, addSeconds = 0) {
  const dateTest = new Date(dateTimeStr); //将-转化为/，使用new Date

  if (addSeconds) {
    dateTest.setSeconds(dateTest.getSeconds() + addSeconds)
  }
  const dateNow = getServerDate() // new Date(); //获取当前时间，这个时间必须从服务器来！！！

  return dateTest.getTime() - dateNow.getTime() > 0
}
function getServerDate() {
  var xhr = null;
  if (window.XMLHttpRequest) {
    xhr = new window.XMLHttpRequest();
  } else { // ie
    xhr = new ActiveObject("Microsoft")
  }

  xhr.open("GET", "/", false)//false不可变
  xhr.send(null);
  var date = xhr.getResponseHeader("Date");
  return new Date(date);
}

function isEmptyObj(obj) {
  if (!obj) {
    return true
  }
  return Object.keys(obj).length == 0 //没有属性，就是空对象！！
}
async function getClientIP() {
  return new Promise((resolve,reject)=>{

    var xhr = new XMLHttpRequest(); // 创建XMLHttpRequest对象
    xhr.open('GET', 'https://ipinfo.io/ip'); // 设置请求类型为GET，指定要访问的URL
    xhr.onreadystatechange = function() { // 注册状态改变事件处理函数
        if (xhr.readyState === 4 && xhr.status === 200) { // 判断请求完成且响应正常
          resolve(xhr.responseText); // 解析服务器返回的JSON字符串            
           // console.log("本地IP地址：" + xhr.responseText); // 输出本地IP地址
        }
    };
       xhr.send(); 
  })


  // debugger
  // const result = await axios('https://ipinfo.io/ip')

}
function getUserIP(onNewIP) {
  let MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  let pc = new MyPeerConnection({
    iceServers: []
  });
  let noop = () => {
  };
  let localIPs = {};
  let ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
  let iterateIP = (ip) => {
    debugger
    if (!localIPs[ip]) onNewIP(ip);
    localIPs[ip] = true;
  };
  pc.createDataChannel('');
  pc.createOffer().then((sdp) => {
    sdp.sdp.split('\n').forEach(function (line) {
      if (line.indexOf('candidate') < 0) return;
      line.match(ipRegex).forEach(iterateIP);
    });
    pc.setLocalDescription(sdp, noop, noop);
  }).catch((reason) => {
  });
  pc.onicecandidate = (ice) => {
    if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
    ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
  };
}

const formatDate = (dateval, needTime = false) => {
  if (dateval) {
    if (needTime) {
      return format(new Date(dateval), 'yyyy/MM/dd HH:mm:ss');
    } else {
      return format(new Date(dateval), 'yyyy/MM/dd');
    }

  } else {
    return null;
  }
}

function ensureArray(sub_scores) {
  let subScores = sub_scores;
  if (!Array.isArray(subScores)) { //如果不是数组，需要转换
    subScores = Object.keys(subScores).map(k => subScores[Number(k)]);
  }
  return subScores;
}
export {
  regString,
  optionOrder,
  ensureArray,
  formatDate,

  getUserIP,
  getClientIP,
  isBeforeTheTime,
  getServerDate,
  isEmptyObj,
  formatDuring
}